package ms.jasim.console.gui;

import java.io.IOException;
import java.util.Collection;

import javax.swing.JScrollPane;
import javax.swing.JTextArea;

import ms.jasim.console.JasimAgent;
import ms.jasim.console.JasimClientListener;
import ms.spm.IAppContext;

import com.vlsolutions.swing.docking.DockKey;

public class AgentStatusDockPane extends DefaultDockPane {
	private static final long serialVersionUID = 1L;
	
	private JTextArea textArea;
	
	public AgentStatusDockPane(IAppContext context) throws IOException {
		super(context);
		createContent();
		refresh();
	}

	@Override
	protected void setupContext() {
		super.setupContext();

		svcJasim.addListener(new JasimClientListener() {
			@Override
			public void notifyListener() {
				try {
					refresh();
				} catch (IOException e) {
				}
			}
		});
	}
	
	private void createContent() {
		setBounds(100, 100, 500, 375);

		textArea = new JTextArea();
		textArea.setInheritsPopupMenu(true);
		textArea.setEditable(false);
		JScrollPane scrollPane = new JScrollPane(textArea);
		scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
		scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);

		add(scrollPane);
	}
	
	@Override
	protected DockKey createDocKey() {
		DockKey key = new DockKey(this.getClass().getName(), "Agent Status", "", null, null);
		key.setMaximizeEnabled(true);
		key.setAutoHideEnabled(true);
		key.setCloseEnabled(true);
		return key;
	}
	
	void refresh() throws IOException {
		Collection<JasimAgent> agents = svcJasim.getAgents();
		if (agents != null) {
			StringBuilder s = new StringBuilder();
			for (JasimAgent ag : agents) {
				s.append("AGENT " + ag.getName() + ":\n");
				for (String st : ag.getStatus())
					s.append("\t" + st + "\n");
			}
			textArea.setText(s.toString());
		} else
			textArea.setText("");
	}
}
